import time

class AHT20:
    def __init__(self, i2c, addr=0x38):
        self.i2c = i2c
        self.addr = addr
        self.state = 0
        self._init_sensor()

    def _init_sensor(self):
        try:
            # 发送初始化命令
            self._send_command([0xBE, 0x08, 0x00])
            time.sleep_ms(10) # 需要时间
        except Exception as e:
            print(f"AHT20 Init Error: {e}")
            self.state = -1
            return
    
    def _soft_reset(self):
        try:
            # 发送软复位命令
            self._send_command(0xBA)
            time.sleep_ms(20) # 需要时间
        except:
            pass
            
    def _send_command(self, cmd):
        self.i2c.writeto(self.addr, bytes(cmd))

    def _read_data(self):
        try:
            self._send_command([0xAC, 0x33, 0x00])
            time.sleep_ms(80)  # 需要时间>75ms
            data = self.i2c.readfrom(self.addr, 6)
            return data
        except Exception as e:
            print(f"Attempt {attempt+1} failed: {e}")
            self.state = -2
            time.sleep_ms(100)
    
    @property
    def temperature(self):
        if self.state != 0:
            return -1
        data = self._read_data()
        temp_raw = ((data[3] & 0x0F) << 16) | (data[4] << 8) | data[5]
        temp = ((temp_raw * 200.0) / 1048576.0) - 50
        return temp

    @property
    def humidity(self):
        if self.state != 0:
            return -1
        data = self._read_data()
        hum_raw = (data[1] << 12) | (data[2] << 4) | (data[3] >> 4)
        hum = (hum_raw * 100.0) / 1048576.0
        return hum
